 struct ListNode {
      int val;
     ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
 };

 /**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(head == nullptr || head->next == nullptr)
            return head;

        ListNode* big_head = new ListNode(0);
        ListNode* big_end = big_head;
        ListNode* small_head = new ListNode(0);
        ListNode* small_end = small_head;

        ListNode* cur = head;
        while(cur)
        {
            ListNode* next = cur->next; // 每次循环内获取next避免空指针就不用单独做判断了
            if(cur->val >= x)
            {
                big_end->next = cur;
                big_end = big_end->next;
            }
            else
            {
                small_end->next = cur;
                small_end = small_end->next;
            }
            cur->next = nullptr; // 断开当前节点与原链表的连接
            cur = next; 
        }

        small_end->next = big_head->next; 

        return small_head->next;
    }
};